'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 发送世界聊天
 * @author sundbcn@gmail.com (sun debing)
 */

var moment = require('moment');
var async = require('async');
var Code = require('../../../consts/code');
var chatType = require('../../../consts/chatType');
var roleModel = require('../../../models/roleModel');
var chatMgr = require('../../../mgr/chatMgr');
var onlineService = require('../../../services/onlineService');
var taskService = require('../../../services/taskService');
var filterSensitiveService = require('../../../services/filterSensitiveService');
var PlayerManager = require('../../../libs/playerManager');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

var handler = Handler.prototype;

/**
 * 发送世界聊天
 */
handler.sendWorld = function (msg, session, next) {
    var role_id = session.uid;
    var content = msg.content;
    var player_manager = new PlayerManager(role_id);

    var param = {};
    var state = false;
    async.waterfall(
        [
            function (cb) {
                player_manager.getModel(
                    ['role', 'task', 'daily_task', 'achieve', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var model = player_manager.role;
                param = {
                    role_id: role_id,
                    type: chatType.ROLE,
                    name: model.getName(),
                    job: model.getJob(),
                    level: model.getLv(),
                    vip: model.getVip(),
                    msg: filterSensitiveService.filter(content),
                    time: moment().unix()
                };

                var time_state = model.getPermanentBanSend();
                var time_state1 = model.getBanSend() <= moment().unix();
                if (time_state1 && time_state === 0) {
                    state = true;
                }

                if (!!state) {
                    // 增加世界聊天次数任务统计
                    taskService.addCompleteChatMsg(player_manager);

                    chatMgr.sendWorld(param, function (err, fails) {
                        if (err) {
                            console.error('send message to world error: %j, fail ids: %j', err, fails);
                            return;
                        }
                        next(null, {
                            code: Code.OK
                        });
                    });
                } else {
                    return next(null, {
                        code: Code.CHAT_USER_BAN_SEND
                    });
                }
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error('get role model error: %j', err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK
            });
        }
    );
};

/**
 * 发送私聊
 */
handler.sendPrivate = function (msg, session, next) {
    var role_id = session.uid;
    var target_role_id = msg.target_role_id;
    var content = msg.content;

    if (!target_role_id || !content) {
        return next();
    }

    var param = {};
    var state = false;
    async.waterfall(
        [

            function (cb) {
                onlineService.checkRoleOnline(target_role_id, cb);
            },
            function (is_online, cb) {
                if (!is_online) {
                    return next(null, {
                        code: Code.CHAT_USER_NOT_ONLINE
                    });
                }

                roleModel.getByRoleId(role_id, cb);
            },
            function (model, cb) {
                param = {
                    role_id: role_id,
                    name: model.getName(),
                    job: model.getJob(),
                    level: model.getLv(),
                    vip: model.getVip(),
                    msg: filterSensitiveService.filter(content),
                    time: moment().unix()
                };
                var time_state = model.getPermanentBanSend();
                var time_state1 = model.getBanSend() <= moment().unix();
                if (!time_state && time_state1) {
                    state = true;
                }

                if (!!state) {
                    chatMgr.sendPrivate(target_role_id, param, function (err) {
                        if (err) {
                            console.error('send message to role %s failed, error: %j', target_role_id, err);
                            return;
                        }
                        next(null, {
                            code: Code.OK
                        });
                    });
                } else {
                    return next(null, {
                        code: Code.CHAT_USER_BAN_SEND
                    });
                }

                cb();
            }
        ],
        function (err) {
            if (!!err) {
                console.error('get role model error: %j', err);
                return;
            }
        }
    );
};

/**
 * 发送军团聊天
 */
handler.sendUnion = function (msg, session, next) {
    var role_id = session.uid;
    var content = msg.content;
    var union_id = 0;
    var state = false;
    var param = {};

    async.waterfall(
        [

            function (cb) {
                roleModel.getByRoleId(role_id, cb);
            },
            function (model, cb) {
                union_id = model.union_id;
                param = {
                    role_id: role_id,
                    name: model.getName(),
                    job: model.getJob(),
                    level: model.getLv(),
                    vip: model.getVip(),
                    msg: filterSensitiveService.filter(content),
                    time: moment().unix()
                };
                var time_state = model.getPermanentBanSend();
                var time_state1 = model.getBanSend() <= moment().unix();
                if (!time_state && time_state1) {
                    state = true;
                }

                cb();
            }
        ],
        function (err) {
            if (!!err) {
                console.error('get role model error: %j', err);
                return;
            }
            if (!!state) {
                chatMgr.sendUnion(union_id, param, function (err, fails) {
                    if (err) {
                        console.error('send message to union error: %j, fail ids: %j', err, fails);
                        return;
                    }
                    next(null, {
                        code: Code.OK
                    });
                });
            } else {
                return next(null, {
                    code: Code.CHAT_USER_BAN_SEND
                });
            }

        }
    );
};

/**
 * 发送走马灯
 */
handler.sendMarquee = function (msg, session, next) {
    var role_id = session.uid;
    var content = msg.content;
    var player_manager = new PlayerManager(role_id);

    var param = {};
    async.waterfall(
        [

            function (cb) {
                roleModel.getByRoleId(role_id, cb);
            },
            function (model, cb) {
                param = {
                    role_id: role_id,
                    type: chatType.SYSTEM,
                    name: model.getName(),
                    job: model.getJob(),
                    level: model.getLv(),
                    vip: model.getVip(),
                    msg: content,
                    time: moment().unix()
                };

                // 增加任务统计
                // taskService.addWorldChat(player_manager);
                cb();
            }
        ],
        function (err) {
            if (!!err) {
                console.error('get role model error: %j', err);
                return;
            }

            chatMgr.sendMarquee(param, function (err, fails) {
                if (err) {
                    console.error('send message to marquee error: %j, fail ids: %j', err, fails);
                    return;
                }
                next(null, {
                    code: Code.OK
                });
            });
        }
    );
};
